<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - 用户管理</title>
    <link rel="stylesheet" href="../css/style.css">
<link href="https://unpkg.com/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="../js/jquery-1.8.3.js"></script>
    <script src="../js/utils.js"></script>
    <script src="../js/api.js"></script>
    <script type="module" src="../js/components/navigation.js"></script>
</head>
<body>
    <div class="app-container">
        <header class="app-header">
            <div class="logo">员工管理系统</div>
            <div class="user-info">
                <span id="username-display"></span>
                <button id="logout-btn" class="btn btn-secondary">退出登录</button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="page-header mb-4">
                    <div class="row">
                        <div class="col-md-6">
                            <h2>用户管理</h2>
                        </div>
                        <div class="col-md-6 text-md-end mt-2 mt-md-0">
                            <a href="#" class="btn btn-primary" id="add-user-btn">
                                <i class="fas fa-plus"></i> 添加用户
                            </a>
                        </div>
                    </div>
                </div>

                <div class="search-bar card mb-4 p-3">
                    <div class="input-group">
                        <input type="text" id="search-input" class="form-control" placeholder="搜索用户名、邮箱或手机号">
                        <button id="search-btn" class="btn btn-secondary">
                            <i class="fas fa-search"></i> 搜索
                        </button>
                        <button id="reset-btn" class="btn btn-outline-secondary">
                            <i class="fas fa-times"></i> 重置
                        </button>
                    </div>
                </div>

                <div class="table-container">
                    <table class="table table-striped table-hover data-table">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>邮箱</th>
                                <th>手机号</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="user-table-body">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
        </div>
        <div class="card-footer">
        <div class="pagination d-flex justify-content-between align-items-center">
            <div class="page-info">第 <span id="current-page">1</span> 页 / 共 <span id="total-pages">0</span> 页</div>
            <div class="page-controls">
                        <button class="btn btn-secondary" id="prev-page">上一页</button>
                        <span id="page-info">第 1 页 / 共 0 页</span>
                        <button class="btn btn-secondary" id="next-page">下一页</button>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div class="modal fade" id="user-modal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content shadow-lg">
            <div class="modal-header">
                <h5 class="modal-title" id="modal-title">添加用户</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="user-form">
                    <input type="hidden" id="user-id" name="id">
                    <div class="form-group">
                        <label for="username">用户名 <span style="color: red;">*</span></label>
                        <input type="text" id="username" name="username" placeholder="请输入用户名">
                    </div>
                    <div class="form-group">
                        <label for="real-name">真实姓名 <span style="color: red;">*</span></label>
                        <input type="text" id="real-name" name="realName" placeholder="请输入真实姓名">
                    </div>
                    <div class="form-group">
                        <label for="email">邮箱 <span style="color: red;">*</span></label>
                        <input type="email" id="email" name="email" placeholder="请输入邮箱">
                    </div>
                    <div class="form-group">
                        <label for="phone">手机号 <span style="color: red;">*</span></label>
                        <input type="tel" id="phone" name="phone" placeholder="请输入手机号">
                    </div>
                    <div class="form-group">
                        <label for="role">角色 <span style="color: red;">*</span></label>
                        <select id="role" name="role">
                            <option value="">请选择角色</option>
                            <option value="admin">管理员</option>
                            <option value="manager">经理</option>
                            <option value="staff">员工</option>
                        </select>
                    </div>
                    <div class="form-group" id="password-group">
                        <label for="password">密码 <span style="color: red;">*</span></label>
                        <input type="password" id="password" name="password" placeholder="请输入密码">
                    </div>
                    <div class="form-group" id="confirm-password-group">
                        <label for="confirm-password">确认密码 <span style="color: red;">*</span></label>
                        <input type="password" id="confirm-password" name="confirmPassword" placeholder="请确认密码">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="save-user-btn" class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button id="cancel-btn" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                $('#username-display').text(username);
            }

            // 退出登录
            /*$('#logout-btn').click(function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });*/

            // 分页按钮
            let currentPage = 1;
            const pageSize = 10;

            // 加载用户数据
            loadUserData();

            // 搜索按钮点击事件
            $('#search-btn').click(function() {
                currentPage = 1;
                loadUserData();
            });

            // 重置按钮点击事件
            $('#reset-btn').click(function() {
                $('#search-input').val('');
                currentPage = 1;
                loadUserData();
            });

            // 搜索输入框回车事件
            $('#search-input').keypress(function(e) {
                if (e.which === 13) {
                    currentPage = 1;
                    loadUserData();
                }
            });

            // 上一页按钮点击事件
            $('#prev-page').click(function() {
                if (currentPage > 1) {
                    currentPage--;
                    loadUserData();
                }
            });

            // 下一页按钮点击事件
            $('#next-page').click(function() {
                // 总页数将在加载数据后更新
                const totalPages = Math.ceil(($('#total-users').text() || 0) / pageSize) || 1;
                if (currentPage < totalPages) {
                    currentPage++;
                    loadUserData();
                }
            });

            // 添加用户按钮点击事件
            $('#add-user-btn').click(function() {
                // 清空表单
                $('#user-form')[0].reset();
                $('#user-id').val('');
                // 显示密码相关字段
                $('#password-group').show();
                $('#confirm-password-group').show();
                // 设置模态框标题
                $('#modal-title').text('添加用户');
                // 显示模态框
                $('#user-modal').modal('show');
            });

            // 关闭模态框
            $('.close-btn, #cancel-btn').click(function() {
                $('#user-modal').modal('hide');
            });

            // 点击模态框外部关闭模态框
            $(window).click(function(event) {
                if (event.target === document.getElementById('user-modal')) {
                    $('#user-modal').hide();
                }
            });

            // 保存用户按钮点击事件
            $('#save-user-btn').click(function() {
                saveUser();
            });

            /*function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }*/

            function loadUserData() {
                const searchKeyword = $('#search-input').val().trim();

                // 调用API加载用户数据
                window.api.user.getList(searchKeyword, currentPage, pageSize)
                    .then(data => {
                        // 更新表格数据
                        updateTableData(data.users);

                        // 更新分页信息
                        updatePagination(data.totalCount);
                    })
                    .catch(error => {
                        console.error('Failed to load user data:', error);
                        alert('加载用户数据失败，请重试');
                    });
            }

            function updateTableData(users) {
                const tableBody = $('#user-table-body');
                tableBody.empty();

                if (users && users.length > 0) {
                    users.forEach(user => {
                        const row = $('<tr></tr>');
                        row.append(`<td>${user.username}</td>`);
                        row.append(`<td>${user.realName}</td>`);
                        row.append(`<td>${user.email}</td>`);
                        row.append(`<td>${user.phone}</td>`);
                        row.append(`<td>${getRoleName(user.role)}</td>`);
                        row.append(`<td><span class="badge ${user.status === 'active' ? 'bg-success' : 'bg-secondary'}">${getStatusName(user.status)}</span></td>`);
                        row.append(`<td>${user.createTime}</td>`);
                        row.append(`<td>
                            <button class="btn btn-sm btn-primary" onclick="editUser(${user.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                            <button class="btn btn-sm btn-secondary" onclick="toggleUserStatus(${user.id}, '${user.status}')">${user.status === 'active' ? '禁用' : '启用'}</button>
                        </td>`);
                        tableBody.append(row);
                    });
                } else {
                    tableBody.append('<tr><td colspan="8" class="no-data">暂无数据</td></tr>');
                }
            }

            function updatePagination(totalCount) {
                const totalPages = Math.ceil(totalCount / pageSize) || 1;
                $('#page-info').text(`第 ${currentPage} 页 / 共 ${totalPages} 页`);

                // 禁用/启用分页按钮
                if (currentPage === 1) {
                    $('#prev-page').prop('disabled', true);
                } else {
                    $('#prev-page').prop('disabled', false);
                }

                if (currentPage >= totalPages) {
                    $('#next-page').prop('disabled', true);
                } else {
                    $('#next-page').prop('disabled', false);
                }
            }

            function saveUser() {
                // 表单验证
                if (!validateUserForm()) {
                    return;
                }

                // 获取表单数据
                const formData = {
                    id: $('#user-id').val().trim(),
                    username: $('#username').val().trim(),
                    realName: $('#real-name').val().trim(),
                    email: $('#email').val().trim(),
                    phone: $('#phone').val().trim(),
                    role: $('#role').val().trim()
                };

                // 如果是添加用户，包含密码
                if (!formData.id) {
                    formData.password = $('#password').val().trim();
                }

                // 调用API保存用户
                const savePromise = formData.id ? 
                    window.api.user.update(formData) : 
                    window.api.user.create(formData);

                savePromise
                    .then(response => {
                        if (response) {
                            alert(formData.id ? '更新成功' : '添加成功');
                            $('#user-modal').hide();
                            loadUserData();
                        } else {
                            alert(formData.id ? '更新失败' : '添加失败');
                        }
                    })
                    .catch(error => {
                        console.error('Failed to save user:', error);
                        alert('保存失败，请重试');
                    });
            }

            function validateUserForm() {
                let isValid = true;

                // 验证用户名
                const username = $('#username').val().trim();
                if (!username) {
                    alert('请输入用户名');
                    isValid = false;
                }

                // 验证真实姓名
                const realName = $('#real-name').val().trim();
                if (!realName) {
                    alert('请输入真实姓名');
                    isValid = false;
                }

                // 验证邮箱
                const email = $('#email').val().trim();
                if (!email || !Validator.isEmail(email)) {
                    alert('请输入有效的邮箱');
                    isValid = false;
                }

                // 验证手机号
                const phone = $('#phone').val().trim();
                if (!phone || !Validator.isPhone(phone)) {
                    alert('请输入有效的手机号');
                    isValid = false;
                }

                // 验证角色
                const role = $('#role').val().trim();
                if (!role) {
                    alert('请选择角色');
                    isValid = false;
                }

                // 如果是添加用户，验证密码
                if (!$('#user-id').val().trim()) {
                    const password = $('#password').val().trim();
                    const confirmPassword = $('#confirm-password').val().trim();

                    if (!password || password.length < 6) {
                        alert('密码长度不能少于6位');
                        isValid = false;
                    }

                    if (password !== confirmPassword) {
                        alert('两次输入的密码不一致');
                        isValid = false;
                    }
                }

                return isValid;
            }

            function getRoleName(roleCode) {
                const roleMap = {
                    'admin': '管理员',
                    'manager': '经理',
                    'staff': '员工'
                };
                return roleMap[roleCode] || roleCode;
            }

            function getStatusName(statusCode) {
                const statusMap = {
                    'active': '启用',
                    'inactive': '禁用'
                };
                return statusMap[statusCode] || statusCode;
            }

            // 全局函数
            window.editUser = function(id) {
                // 加载用户详情
                window.api.user.getById(id)
                    .then(user => {
                        if (user) {
                            // 填充表单
                            $('#user-id').val(user.id);
                            $('#username').val(user.username);
                            $('#real-name').val(user.realName);
                            $('#email').val(user.email);
                            $('#phone').val(user.phone);
                            $('#role').val(user.role);
                            // 隐藏密码相关字段
                            $('#password-group').hide();
                            $('#confirm-password-group').hide();
                            // 设置模态框标题
                            $('#modal-title').text('编辑用户');
                            // 显示模态框
                            $('#user-modal').show();
                        } else {
                            alert('未找到用户信息');
                        }
                    })
                    .catch(error => {
                        console.error('Failed to load user info:', error);
                        alert('加载用户信息失败，请重试');
                    });
            };

            window.deleteUser = function(id) {
                if (confirm('确定要删除该用户吗？')) {
                    window.api.user.delete(id)
                        .then(response => {
                            if (response) {
                                alert('删除成功');
                                loadUserData();
                            } else {
                                alert('删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('Failed to delete user:', error);
                            alert('删除失败，请重试');
                        });
                }
            };

            window.toggleUserStatus = function(id, currentStatus) {
                const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
                const actionText = newStatus === 'active' ? '启用' : '禁用';

                if (confirm(`确定要${actionText}该用户吗？`)) {
                    window.api.user.updateStatus(id, newStatus)
                        .then(response => {
                            if (response) {
                                alert(`${actionText}成功`);
                                loadUserData();
                            } else {
                                alert(`${actionText}失败`);
                            }
                        })
                        .catch(error => {
                            console.error(`Failed to ${actionText} user:`, error);
                            alert(`${actionText}失败，请重试`);
                        });
                }
            };
        });
    </script>
</body>
</html>